import React, {memo, useCallback, useEffect, useState} from 'react';
import {Collapse, Menu, Dropdown, Modal, Input, Button} from 'antd';
import {
  CaretRightOutlined,
  SettingOutlined,
  EditOutlined,
  DeleteOutlined,
  SoundOutlined,
  PlusSquareOutlined
} from '@ant-design/icons';
import {
  createClassify,
  deleteClassify,
  getArticleClassify,
  updateClassify
} from "@/network/archives.request";
import {ArchivesWrapper} from "./style";
import AdminArticleList from "@/components/admin-article-list";
import setMessage from "@/utils/setMessage";

const {Panel} = Collapse;

export default memo(function Archives(props) {
  const {userId} = props;
  const [classifyList, setClassifyList] = useState([]);
  const [currentId, setCurrentId] = useState();
  const [currentContent, setCurrentContent] = useState("");
  const [visible, setVisible] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [modalTitle, setModalTitle] = useState("");
  const [newClassify, setNewClassify] = useState("");

  const changeData = useCallback(() => {
    getArticleClassify(userId).then(res => {
      setClassifyList(res);
    }).catch(console.log)
  }, [userId])

  useEffect(() => {
    changeData();
  }, [changeData])

  const modalText = () => {
    let deleteTemplate = (<>
      <div className="pb-3 pl-5">确定删除归档 {currentContent}?</div>
      <i className="fs-1"><SoundOutlined className="pr-3" style={{color: "#ff5577"}}/>删除后该归档下的所有文章都被删除, 主上三思啊~</i>
    </>)
    let updateTemplate = (<>
      <Input value={currentContent} autoFocus onChange={e => setCurrentContent(e.target.value)}/>
    </>)
    let createTemplate = (<>
      <Input value={newClassify} placeholder="请输入归档名" autoFocus onChange={e => setNewClassify(e.target.value)}/>
    </>)
    return modalTitle === "修改" ? updateTemplate : (modalTitle === "新增" ? createTemplate : deleteTemplate);
  }

  const showUpdateModal = useCallback((e) => {
    e.stopPropagation();
    setModalTitle("修改");
    setVisible(true);
  }, [])

  const showDeleteModal = useCallback((e) => {
    e.stopPropagation();
    setModalTitle("删除");
    setVisible(true);
  }, [])

  const menu = useCallback(() => (
    <Menu>
      <Menu.Item icon={<EditOutlined/>}>
        <span onClick={showUpdateModal}>修改名称</span>
      </Menu.Item>
      <Menu.Item danger icon={<DeleteOutlined/>}>
        <span onClick={showDeleteModal}>删除归档</span>
      </Menu.Item>
    </Menu>
  ), [showUpdateModal, showDeleteModal])

  const genExtra = useCallback((classifyId, classify) => {
    return (
      <Dropdown overlay={menu} arrow trigger={['click']}>
        <SettingOutlined
          className="pr-5"
          onClick={event => {
            setCurrentId(classifyId);
            setCurrentContent(classify);
            event.stopPropagation();
          }}
        />
      </Dropdown>
    );
  }, [menu])

  const handleOk = () => {
    if (modalTitle === "修改" && currentContent.trim().length > 0) {
      setConfirmLoading(true);
      updateClassify(currentId, currentContent).then(res => {
        if(res){
          res.affectedRows && changeData();
          res.affectedRows && setMessage("修改成功", "success");
        }else{
          setMessage("归档已存在", "error");
        }
        setVisible(false);
        setConfirmLoading(false);
      }).catch(error => {
        setMessage("修改失败", "error");
        setVisible(false);
        setConfirmLoading(false);
        console.log(error);
      })
    }
    if (modalTitle === "删除") {
      setConfirmLoading(true);
      deleteClassify(currentId).then(res => {
        res.affectedRows && changeData();
        res.affectedRows && setMessage("删除成功", "success");
        setVisible(false);
        setConfirmLoading(false);
      }).catch(error => {
        setMessage("删除失败", "error");
        setVisible(false);
        setConfirmLoading(false);
        console.log(error)
      })
    }
    if (modalTitle === "新增" && newClassify.trim().length > 0) {
      setConfirmLoading(true);
      createClassify(newClassify).then(res => {
        if (res) {
          res.affectedRows && changeData();
          res.affectedRows && setMessage("新增成功", "success");
        } else {
          setMessage("归档已存在", "error");
        }
        setNewClassify("");
        setVisible(false);
        setConfirmLoading(false);
      }).catch(error => {
        setMessage("新增失败", "error");
        setVisible(false);
        setConfirmLoading(false);
        console.log(error)
      })
    }
  };

  const addClassify = useCallback(() => {
    setModalTitle("新增");
    setVisible(true);
  }, [])

  return (
    <ArchivesWrapper>
      <div className="pb-5">
        <Button onClick={addClassify} type="primary" ghost icon={<PlusSquareOutlined/>} size="middle">
          新建归档
        </Button>
      </div>
      <Collapse
        accordion
        bordered={false}
        expandIcon={({isActive}) => <CaretRightOutlined rotate={isActive ? 90 : 0}/>}
        className="site-collapse-custom-collapse no-scrollbar"
        style={{maxHeight: "75vh", overflowY: "scroll"}}
      >
        {
          classifyList && classifyList.length > 0 && classifyList.map((item) => {
            return (
              <Panel
                header={item.classify + `（${item.count}）`}
                key={item.id}
                className="site-collapse-custom-panel"
                extra={genExtra(item.id, item.classify)}
              >
                <AdminArticleList userId={props.userId} classifyId={item.id}/>
              </Panel>
            )
          })
        }
      </Collapse>

      <Modal
        title={modalTitle}
        visible={visible}
        onOk={handleOk}
        cancelText="取消"
        okText="确定"
        confirmLoading={confirmLoading}
        onCancel={e => setVisible(false)}
      >
        <div>{modalText()}</div>
      </Modal>

    </ArchivesWrapper>
  )
})